﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Missbot.Common;
using Dolany.UtilityTool;

namespace Missbot.Core.SyntaxChecker
{
    /// <summary>
    /// 语法检查服务
    /// </summary>
    public class SyntaxCheckerSvc : ISingleton
    {
        private List<IParam> ParamCheckers { get; }

        private IParam this[Type checkType] => ParamCheckers.FirstOrDefault(c => c.CheckType == checkType);

        public SyntaxCheckerSvc()
        {
            ParamCheckers = AutofacSvc.LoadAllInstanceFromInterface<IParam>();
        }

        /// <summary>
        /// 语法检查  
        /// </summary>
        /// <param name="parameterInfos"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public (bool isValid, List<object> @params) SyntaxCheck(IEnumerable<ParameterInfo> parameterInfos, string msg)
        {
            msg = msg.SplitParam().unsolvedStr.Trim(); // 把命令前缀去除后再解析参数
            if (parameterInfos.IsNullOrEmpty())
            {
                return string.IsNullOrEmpty(msg) ? (true, new List<object>()) : (false, null);
            }
            
            var @params = new List<object>();
            foreach (var parameterInfo in parameterInfos)
            {
                var paramType = parameterInfo.ParameterType;
                var paramChecker = this[paramType];
                var (isValid, param, unsolvedMsg) = paramChecker.Check(msg);

                if (!isValid)
                {
                    return (false, null);
                }
                
                @params.Add(param);
                msg = unsolvedMsg;
            }

            return string.IsNullOrEmpty(msg.Trim()) ? (true, @params) : (false, null);
        }
    }
}